package com.weasel.helper;

import org.apache.commons.lang.StringUtils;

import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;

/**
 * Created by Dylan on 2015/9/28.
 */
public final class ClassPathFileReader {

    /**
     * @param path
     * @return
     */
    public static InputStream readToInputStrream(String path){

        path = resolvePath(path);
        return ClassLoader.getSystemResourceAsStream(path);
    }

    /**
     * @param path
     * @return
     */
    public static File readToFile(String path){
        path = resolvePath(path);
        return new File(ClassLoader.getSystemResource(path).getFile());
    }

    /**
     * @return
     */
    public static String getClassPath(){

        return StringUtils.removeStart(ClassLoader.getSystemResource("").toString(),"file:/");
    }

    /**
     * @param path
     * @return
     * @throws IOException
     */
    public static String readToString(String path) throws IOException {
            InputStream is = null;
            ByteArrayOutputStream baos = null;
        try{
            is = readToInputStrream(path);
            baos = new ByteArrayOutputStream();
            byte [] datas = new byte[1024];
            int count = -1;
            while ((count = is.read(datas,0,1024)) != -1){
                baos.write(datas,0,count);
            }
            return new String(baos.toByteArray(),"utf8");
        }finally {
            if(null != is){
                is.close();
            }
            if(null != baos){
                baos.close();
            }

        }
    }

    private static String resolvePath(String path){

        path = StringUtils.removeStart(path,"classpath:");
        path = StringUtils.removeStart(path,"/");
        return path;
    }

    private ClassPathFileReader(){}
}
